package com.yonghui.springsecurityoauth2demo.exception;


import com.yonghui.springsecurityoauth2demo.pojo.AjaxResult;
import com.yonghui.springsecurityoauth2demo.pojo.ResultCode;
import com.yonghui.springsecurityoauth2demo.pojo.ResultVo;
import com.yonghui.springsecurityoauth2demo.utils.CarcheckStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.RedirectMismatchException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 全局异常处理器
 * 
 * @author admin
 */
@ControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN.value(), "没有权限，请联系管理员授权");
    }

    @ResponseBody
    @ExceptionHandler(UnsupportedGrantTypeException.class)
    public ResultVo handleUnsupportedGrantTypeException(UnsupportedGrantTypeException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        ResultCode resultCode = ResultCode.UNSUPPORTED_GRANT_TYPE;
        return new ResultVo(resultCode.getCode(),resultCode.getMsg(),null);
    }

    @ResponseBody
    @ExceptionHandler(InvalidGrantException.class)
    public ResultVo handleInvalidGrantException(InvalidGrantException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        ResultCode resultCode = null;
        String message = e.getMessage();
        if(message.contains("Invalid authorization code")){
            resultCode = ResultCode.CODE_ERROR;
        }
        return new ResultVo(resultCode.getCode(),resultCode.getMsg(),null);
    }

    @ResponseBody
    @ExceptionHandler(InvalidClientException.class)
    public ResultVo handleInvalidClientException(InvalidClientException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        ResultCode resultCode = ResultCode.CLIENT_ERROR;
        return new ResultVo(resultCode.getCode(),resultCode.getMsg(),null);
    }

    @ResponseBody
    @ExceptionHandler(InvalidScopeException.class)
    public ResultVo handleInvalidScopeException(InvalidScopeException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        ResultCode resultCode = ResultCode.SCOPE_ERROR;
        return new ResultVo(resultCode.getCode(),resultCode.getMsg(),null);
    }

    @ResponseBody
    @ExceptionHandler(RedirectMismatchException.class)
    public ResultVo handleRedirectMismatchException(RedirectMismatchException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        ResultCode resultCode = ResultCode.REDIRECT_URI_ERROR;
        return new ResultVo(resultCode.getCode(),resultCode.getMsg(),null);
    }

    @ResponseBody
    @ExceptionHandler(InvalidTokenException.class)
    public ResultVo handleInvalidTokenException(InvalidTokenException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        ResultCode resultCode = ResultCode.TOKEN_ERROR;
        return new ResultVo(resultCode.getCode(),resultCode.getMsg(),null);
    }

    @ExceptionHandler(BadCredentialsException.class)
    public AjaxResult handleBadCredentialsException(BadCredentialsException e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN.value(), "用户名或密码不正确");
    }

//    @ExceptionHandler(BadCredentialsException.class)
//    public ModelAndView handleBadCredentialsException2(BadCredentialsException e, HttpServletRequest request, HttpServletResponse response) {
//        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
//
//        ModelAndView mav = new ModelAndView("login");
//        mav.addObject("errorMessage", "用户名或密码不正确");
//        return mav;
//    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
            HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request, HttpServletResponse response)
    {

        LOGGER.error(e.getMessage(), e);
        Integer code = e.getCode();

        return CarcheckStringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request, HttpServletResponse response)
    {

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',发生未知异常.", requestURI, e);

        return AjaxResult.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request, HttpServletResponse response)
    {
        response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());

        String requestURI = request.getRequestURI();
        LOGGER.error("请求地址'{}',发生系统异常.", requestURI, e);
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException e)
    {
        LOGGER.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
    {
        LOGGER.error(e.getMessage(), e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return AjaxResult.error(message);
    }
}
